package com.gcloud.mesh.dcs.task;


import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.smc20190601.models.DescribeReplicationJobsResponseBody;
import com.gcloud.mesh.asset.service.ICloudResourceService;
import com.gcloud.mesh.dcs.dao.AppDao;
import com.gcloud.mesh.dcs.dao.SchedulerJobDao;
import com.gcloud.mesh.dcs.dao.SchedulerStepDao;
import com.gcloud.mesh.dcs.entity.SchedulerJobEntity;
import com.gcloud.mesh.dcs.entity.SchedulerStepEntity;
import com.gcloud.mesh.dcs.enums.SchedulerJobStatus;
import com.gcloud.mesh.dcs.enums.SchedulerStepStatus;
import com.gcloud.mesh.dcs.strategy.IReleaseNode;
import com.gcloud.mesh.dcs.strategy.ServerMigrationStrategyContext;
import com.gcloud.mesh.dcs.strategy.process.AliMigrationProcess;
import com.gcloud.mesh.header.vo.dcs.ALiVMInstantInfoVO;
import com.gcloud.mesh.supplier.dao.SupplierDao;
import com.gcloud.mesh.supplier.entity.SupplierEntity;
import com.gcloud.mesh.supplier.enums.SystemType;

import lombok.extern.slf4j.Slf4j;


/**
 * 检测虚拟机迁移任务状态 status = 2 scheduler_type in ('ali','huawei')
 */

@Slf4j
//@Component
public class CheckVMStatusTask {

    @Autowired
    private SchedulerStepDao schedulerStepDao;

    @Autowired
    private SchedulerJobDao schedulerJobDao;

    @Autowired
    private SupplierDao supplierDao;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ServerMigrationStrategyContext serverMigrationStrategyContext;

    @Autowired
    private AliMigrationProcess aliMigrationProcess;

    @Autowired
    private ICloudResourceService cloudResourceService;
    @Autowired
    private AppDao appDao;
    @Autowired
    private IReleaseNode releaseNode;


    @Scheduled(fixedDelay = 1000 * 30)
    public void doExec() {
        String uuid = UUID.randomUUID().toString();
//        try {
        log.info(uuid + "[CheckVMStatusTask] 检测虚拟机迁移任务状态定时器开始");
        String sql = "select * from dcs_scheduler_steps t where " +
                " t.status = 1 and scheduler_type in ('ali','huawei') and end_time is null " +
                " and now() < TIMESTAMPADD(MINUTE, 12*60, begin_time)" +
                " order by begin_time" +
                "";
        List<SchedulerStepEntity> stepEntityList = schedulerStepDao.findBySql(sql, SchedulerStepEntity.class);
        if (stepEntityList != null && !stepEntityList.isEmpty()) {
            log.info(uuid + "一共需要同步" + stepEntityList.size() + "个任务");
            int finish = 0;
            for (SchedulerStepEntity schedulerStepEntity : stepEntityList) {
                Boolean result =false;
                try {
                    result = serverMigrationStrategyContext.checkStatus(
                            SystemType.getSystemTypeByName(schedulerStepEntity.getSchedulerType()).getName(),
                            schedulerStepEntity.getStepNo(), schedulerStepEntity.getAttach()
                    );
                }catch (Exception e){
                    log.error(schedulerStepEntity.getSchedulerJobId()+"查询同步状态异常",e);
                }
                SchedulerJobEntity schedulerJobEntity = schedulerJobDao.getById(schedulerStepEntity.getSchedulerJobId());
                try {
                    if (result) {
                        finish++;
                        schedulerStepEntity.setEndTime(new Date());
                        schedulerStepEntity.setStatus(SchedulerStepStatus.SUCCESS.getValue());
                        schedulerStepDao.update(schedulerStepEntity);
                        SchedulerJobEntity jobEntity = schedulerJobDao.getById(schedulerStepEntity.getSchedulerJobId());
                        SupplierEntity supplierEntity = supplierDao.findOneByProperty("datacenterId", jobEntity.getSrcDatacenterId());
                        if (SystemType.ALI.getName().equalsIgnoreCase(supplierEntity.getType())) {
                            JSONObject json = JSONObject.parseObject(schedulerStepEntity.getAttach());
                            String destRegionId = json.getString("destRegionId");
                            String srcRegionId = json.getString("srcRegionId");
                            String srcInstanceId = json.getString("srcInstanceId");
                            String accessKeyId = json.getString("accessKeyId");
                            String accessSecret = json.getString("accessSecret");
                            String myJobId = json.getString("myJobId");
                            String imageId = json.getString("imageId");
                            if(StringUtils.isBlank(imageId)){
                                String jobId = json.getString("jobId");
                                String sourceId = json.getString("sourceId");
                                DescribeReplicationJobsResponseBody.DescribeReplicationJobsResponseBodyReplicationJobsReplicationJob dd = aliMigrationProcess.describeReplicationJobs(accessKeyId, accessSecret, jobId, sourceId);
                                imageId = dd.getImageId();
                                redisUtil.set("migration:ali:image:"+srcInstanceId,imageId,24*60*60);
                            }
                            ALiVMInstantInfoVO vo = null;
                            Object srcObj = redisUtil.get("migration:ali:srcInstance:" + myJobId);
                            if (srcObj == null) {
                                //获取源实例信息
                                vo = aliMigrationProcess.getSrcInstanceInfo(myJobId, accessKeyId, accessSecret, srcRegionId, srcInstanceId,10);
                            } else {
                                //获取源实例信息
                                vo = JSONObject.toJavaObject(JSONObject.parseObject(srcObj.toString()), ALiVMInstantInfoVO.class);
                            }
                            //创建实例
                            String instanceId = aliMigrationProcess.createInstance(myJobId, accessKeyId, accessSecret, destRegionId, imageId, vo);

                            TimeUnit.SECONDS.sleep(60);
                            //启动实例
                            aliMigrationProcess.startInstance(myJobId, accessKeyId, accessSecret, destRegionId, instanceId,10);

                            TimeUnit.SECONDS.sleep(60);
                            //分配实例公网IP
                            String ip = aliMigrationProcess.allocatePublicIpAddress(myJobId, accessKeyId, accessSecret, destRegionId, instanceId,10);

                            schedulerStepDao.updateLastSetpName(myJobId, String.format("分配实例公网IP（%s）", ip));
                            aliMigrationProcess.deleteSrcInstanct(myJobId, accessKeyId, accessSecret, srcRegionId, srcInstanceId);

                            //修改app 表的 id
//                            appDao.updateAppIdBySrcId(myJobId, srcInstanceId, instanceId);
//                            cloudResourceService.updateMigrationResult(instanceId, schedulerJobEntity.getDstDatacenterId(), schedulerJobEntity.getDstNodeId(), schedulerJobEntity.getSchedulerModel().toString());
                            
                            //增加阿里的释放资源
                        } else {
//                            cloudResourceService.updateMigrationResult(schedulerJobEntity.getAppId(), schedulerJobEntity.getDstDatacenterId(), schedulerJobEntity.getDstNodeId(), schedulerJobEntity.getSchedulerModel().toString());
                        }
                        schedulerJobDao.updateJobStatusById(schedulerStepEntity.getSchedulerJobId(), SchedulerJobStatus.SUCCESS);
                        //zhangdp添加阿里云资源
                        releaseNode.releaseNode(schedulerJobEntity.getSourceNodeId());
                    
                    } else {
                        log.info(uuid + "任务状态为：" + result + "，跳过处理");
                    }
                } catch (Exception e) {
                    log.error("同步状态失败", e);
                    schedulerJobDao.updateJobStatus(schedulerJobEntity, SchedulerJobStatus.FAIL);
                }
            }
            log.info(uuid + "已完成同步" + finish + "个");
        } else {
            log.info(uuid + "没有需要同步状态的任务");
        }

        log.info(uuid + "[CheckVMStatusTask]检测虚拟机迁移任务状态定时器结束");


    }


}
